package DoulblyLinked;

public class DoublyLinkedList {
    //链表的头结点
    Node head;

    //添加节点到链表的尾部
    public void add(int data) {
        Node node = new Node(data);
        //如果链表为空那么新节点作为头结点
        if (head == null) {
            head = node;
        } else {
            //找到链表的尾部进行插入
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            //将新节点的前指针指向前结点
            node.prev = current;
            //将当前节点的尾部指向新节点
            current.next = node;
        }
    }

    //添加节点到指定位置
    public void insertAfter(Node node, int data) {
        if (node == null) {
            System.out.println("指定节点为空插入失败");
            return;
        }
        //创建新节点
        Node newNode = new Node(data);
        //将新节点前指针指向指定节点
        newNode.prev = node;
        //将新节点的后指针指向后节点
        newNode.next = node.next;

        //如果指定节点的下一个节点有值，就让下一个的prev指向当前新插入的节点
        if (node.next != null) {
            node.next.prev = newNode;
        }
        //将上一个节点指向插入的节点
        node.next = newNode;
    }

    //在链表中查找节点
    public Node find(int data) {
        Node current = head;
        while (current.next != null) {
            if (current.data == data) {
                return current;
            }
            current = current.next;
        }
        return null;
    }

    //在链表中删除指定节点
    public void delete(int data) {
        //从链表的头结点开始找
        Node current = head;
        while (current != null) {
            if (current.data == data) {
                //如果是非头结点
                if (current.prev != null) {
                    current.prev.next = current.next;
                } else {
                    //如果是头结点
                    head = current.next;
                }
                if (current.next != null) {
                    //将要删除节点的后节点的前驱指向要删除的前驱
                    current.next.prev = current.next;
                }
                return;
            }
            current = current.next;
        }
    }

    public void print() {
        Node current = head;
        while (current != null) {
            System.out.println(current.data);
            current = current.next;
        }
    }

}
